<!-- cart.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车 - 鲜时蔬</title>
    <!-- 引入Vue.js -->
    <script src="../../js/vue.js"></script>
    <!-- 引入Element UI样式 -->
    <link rel="stylesheet" href="../../css/index.css">
    <!-- 引入Element UI组件库 -->
    <script src="../../js/index.js"></script>
    <!-- 引入axios -->
    <script src="../../js/axios.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
            background-color: #f5f5f5;
            color: #333;
        }

        .container {
            width: 1140px;
            margin: 0 auto;
            padding: 0 15px;
        }

        @media (max-width: 1199px) {
            .container {
                width: 960px;
            }
        }

        @media (max-width: 991px) {
            .container {
                width: 720px;
            }
        }

        @media (max-width: 767px) {
            .container {
                width: 100%;
            }
        }

        /* 导航栏 */
        .header {
            background: #fff;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1000;
        }

        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 0;
        }

        .logo {
            display: flex;
            align-items: center;
            font-size: 20px;
            font-weight: bold;
            color: #27ae60;
            text-decoration: none;
        }

        .logo i {
            margin-right: 8px;
        }

        .nav {
            display: flex;
        }

        .nav a {
            margin: 0 15px;
            text-decoration: none;
            color: #666;
            font-size: 14px;
            padding: 5px 0;
        }

        .nav a.active {
            color: #27ae60;
            border-bottom: 2px solid #27ae60;
        }

        .user-actions {
            display: flex;
            align-items: center;
            position: relative;
        }

        .user-actions button {
            margin-left: 15px;
            background: none;
            border: none;
            color: #666;
            cursor: pointer;
            font-size: 14px;
            display: flex;
            align-items: center;
        }

        .user-actions button i {
            margin-right: 5px;
        }

        /* 用户信息下拉菜单 */
        .user-info {
            position: relative;
            display: flex;
            align-items: center;
            cursor: pointer;
        }

        .user-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background-color: #27ae60;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 8px;
            font-size: 14px;
        }

        .user-dropdown {
            position: absolute;
            top: 100%;
            right: 0;
            background: white;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            border-radius: 4px;
            padding: 5px 0;
            min-width: 120px;
            z-index: 10;
            margin-top: 5px;
            display: none;
        }

        .user-dropdown.show {
            display: block;
        }

        .user-dropdown-item {
            padding: 8px 15px;
            font-size: 14px;
            color: #606266;
            cursor: pointer;
        }

        .user-dropdown-item:hover {
            background-color: #f5f7fa;
            color: #27ae60;
        }

        /* 主内容区 */
        .main {
            padding-top: 80px;
            padding-bottom: 50px;
        }

        /* 页面标题 */
        .page-title {
            font-size: 24px;
            color: #333;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        /* 购物车内容 */
        .cart-content {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            padding: 20px;
        }

        /* 购物车表头 */
        .cart-header {
            display: grid;
            grid-template-columns: 3fr 1fr 1fr 1fr 1fr;
            padding: 15px 0;
            border-bottom: 1px solid #eee;
            font-weight: bold;
            color: #666;
        }

        /* 购物车商品项 */
        .cart-item {
            display: grid;
            grid-template-columns: 3fr 1fr 1fr 1fr 1fr;
            padding: 20px 0;
            border-bottom: 1px solid #eee;
            align-items: center;
        }

        .cart-item:last-child {
            border-bottom: none;
        }

        /* 商品信息 */
        .product-info {
            display: flex;
            align-items: center;
        }

        .product-image {
            width: 80px;
            height: 80px;
            object-fit: cover;
            border-radius: 4px;
            margin-right: 15px;
        }

        .product-details h4 {
            margin: 0 0 5px 0;
            font-size: 16px;
            color: #333;
        }

        .product-details p {
            margin: 0;
            font-size: 14px;
            color: #999;
        }

        /* 单价 */
        .unit-price {
            text-align: center;
            font-size: 16px;
            font-weight: bold;
            color: #e74c3c;
        }

        /* 数量控制 */
        .quantity-control {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .quantity-btn {
            background-color: #f8f9fa;
            border: 1px solid #ddd;
            width: 30px;
            height: 30px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
        }

        .quantity-input {
            width: 50px;
            text-align: center;
            border: 1px solid #ddd;
            height: 30px;
            margin: 0 5px;
        }

        /* 小计 */
        .subtotal {
            text-align: center;
            font-size: 16px;
            font-weight: bold;
            color: #e74c3c;
        }

        /* 操作按钮 */
        .action-btn {
            text-align: center;
        }

        .action-btn button {
            background: none;
            border: none;
            color: #999;
            cursor: pointer;
            font-size: 16px;
        }

        .action-btn button:hover {
            color: #e74c3c;
        }

        /* 购物车汇总 */
        .cart-summary {
            margin-top: 30px;
            background: #f9f9f9;
            border-radius: 4px;
            padding: 20px;
            display: flex;
            justify-content: flex-end;
        }

        .summary-content {
            width: 300px;
        }

        .summary-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
        }

        .summary-total {
            display: flex;
            justify-content: space-between;
            margin: 15px 0;
            padding-top: 15px;
            border-top: 1px solid #eee;
            font-size: 18px;
            font-weight: bold;
        }

        .total-amount {
            color: #e74c3c;
        }

        .checkout-btn {
            width: 100%;
            background-color: #e74c3c;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 12px;
            font-size: 16px;
            cursor: pointer;
            text-align: center;
            display: block;
            text-decoration: none;
        }

        .checkout-btn:hover {
            background-color: #c0392b;
        }

        .empty-cart {
            text-align: center;
            padding: 50px 0;
        }

        .empty-cart i {
            font-size: 64px;
            color: #ddd;
            margin-bottom: 20px;
        }

        .empty-cart p {
            font-size: 18px;
            color: #999;
            margin-bottom: 20px;
        }

        .continue-shopping {
            display: inline-block;
            background-color: #27ae60;
            color: white;
            padding: 10px 20px;
            border-radius: 4px;
            text-decoration: none;
        }

        .continue-shopping:hover {
            background-color: #219653;
        }

        /* 页脚 */
        .footer {
            background: #333;
            color: #fff;
            padding: 30px 0;
            margin-top: 50px;
        }

        .footer-content {
            text-align: center;
            font-size: 14px;
        }

        /* 加载状态 */
        .loading {
            text-align: center;
            padding: 50px;
        }

        /* 响应式设计 */
        @media (max-width: 767px) {
            .cart-header,
            .cart-item {
                grid-template-columns: 2fr 1fr;
                grid-row-gap: 10px;
            }

            .cart-header > div:nth-child(2),
            .cart-header > div:nth-child(3),
            .cart-header > div:nth-child(4),
            .cart-item > div:nth-child(2),
            .cart-item > div:nth-child(3),
            .cart-item > div:nth-child(4) {
                display: none;
            }

            .cart-item {
                position: relative;
                padding-bottom: 40px;
            }

            .unit-price-mobile,
            .quantity-mobile,
            .subtotal-mobile {
                display: flex;
                justify-content: space-between;
                margin-top: 5px;
            }

            .action-btn {
                position: absolute;
                right: 0;
                bottom: 10px;
            }

            .cart-summary {
                justify-content: center;
            }

            .summary-content {
                width: 100%;
            }
        }
    </style>
</head>
<body>
<div id="app">
    <!-- 导航栏 -->
    <header class="header">
        <div class="container">
            <div class="header-content">
                <a href="index.html" class="logo">
                    <i class="el-icon-shopping-bag"></i>
                    <span>鲜时蔬</span>
                </a>
                <nav class="nav">
                    <a href="index.html">首页</a>
                    <a href="vegetables.html">蔬菜列表</a>
                    <a href="contact.html">联系我们</a>
                </nav>
                <div class="user-actions">
                    <!-- 根据登录状态显示不同内容 -->
                    <template v-if="isLoggedIn">
                        <div class="user-info" @mouseenter="showDropdown = true" @mouseleave="showDropdown = false">
                            <div class="user-avatar">
                                {{ userInfo.nickName ? userInfo.nickName.charAt(0) : userInfo.userName.charAt(0) }}
                            </div>
                            <span>{{ userInfo.nickName || userInfo.userName }}</span>
                            <div class="user-dropdown" :class="{ 'show': showDropdown }">
                                <div class="user-dropdown-item" @click="goToPersonalCenter">个人中心</div>
                                <div class="user-dropdown-item" @click="goToAccountManagement">账号管理</div>
                                <div class="user-dropdown-item" @click="logout">退出登录</div>
                            </div>
                        </div>
                    </template>
                    <template v-else>
                        <button @click="goToLogin">
                            <i class="el-icon-user"></i> 登录
                        </button>
                    </template>
                    <button @click="goToCart">
                        <i class="el-icon-shopping-cart"></i> 购物车({{ cartCount }})
                    </button>
                </div>
            </div>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="main">
        <div class="container">
            <div class="page-title">
                <h1>购物车</h1>
                <div v-if="cartItems.length > 0">
                    <el-button type="danger" @click="clearCart" size="small">清空购物车</el-button>
                </div>
            </div>

            <div class="cart-content">
                <div v-if="loading" class="loading">
                    <el-spinner style="margin: 50px auto;"></el-spinner>
                    <p>正在加载购物车数据...</p>
                </div>

                <div v-else-if="cartItems.length === 0" class="empty-cart">
                    <i class="el-icon-shopping-cart-2"></i>
                    <p>购物车还是空的，快去挑选商品吧！</p>
                    <a href="index.html" class="continue-shopping">继续购物</a>
                </div>

                <div v-else>
                    <!-- 购物车表头 -->
                    <div class="cart-header">
                        <div>商品信息</div>
                        <div>单价</div>
                        <div>数量</div>
                        <div>小计</div>
                        <div>操作</div>
                    </div>

                    <!-- 购物车商品项 -->
                    <div class="cart-item" v-for="item in cartItems" :key="item.cartId">
                        <div class="product-info">
                            <img :src="item.product.imageUrl || '/static/images/no-image.png'"
                                 :alt="item.product.productName"
                                 class="product-image"
                                 @error="handleImageError($event)">
                            <div class="product-details">
                                <h4>{{ item.product.productName }}</h4>
                                <p>商品编号: {{ item.product.productCode }}</p>
                            </div>
                        </div>
                        <div class="unit-price">¥{{ item.product.price }}</div>
                        <div class="quantity-control">
                            <button class="quantity-btn" @click="updateQuantity(item, -1)">-</button>
                            <input type="number"
                                   class="quantity-input"
                                   :value="item.quantity"
                                   @change="updateQuantityInput(item, $event)"
                                   min="1">
                            <button class="quantity-btn" @click="updateQuantity(item, 1)">+</button>
                        </div>
                        <div class="subtotal">¥{{ (item.product.price * item.quantity).toFixed(2) }}</div>
                        <div class="action-btn">
                            <button @click="removeFromCart(item.cartId)">
                                <i class="el-icon-delete"></i>
                            </button>
                        </div>

                        <!-- 移动端显示 -->
                        <div class="unit-price-mobile" style="display: none;">
                            <span>单价:</span>
                            <span>¥{{ item.product.price }}</span>
                        </div>
                        <div class="quantity-mobile" style="display: none;">
                            <span>数量:</span>
                            <span>{{ item.quantity }}</span>
                        </div>
                        <div class="subtotal-mobile" style="display: none;">
                            <span>小计:</span>
                            <span>¥{{ (item.product.price * item.quantity).toFixed(2) }}</span>
                        </div>
                    </div>

                    <!-- 购物车汇总 -->
                    <div class="cart-summary">
                        <div class="summary-content">
                            <div class="summary-row">
                                <span>商品总数:</span>
                                <span>{{ totalItems }}</span>
                            </div>
                            <div class="summary-row">
                                <span>商品金额:</span>
                                <span>¥{{ totalAmount.toFixed(2) }}</span>
                            </div>
                            <div class="summary-total">
                                <span>总计:</span>
                                <span class="total-amount">¥{{ totalAmount.toFixed(2) }}</span>
                            </div>
                            <a href="#" class="checkout-btn" @click.prevent="goToCheckout">去结算</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="footer">
        <div class="container">
            <div class="footer-content">
                <p>© 2025 鲜时蔬 版权所有 | 京ICP备12345678号</p>
            </div>
        </div>
    </footer>
</div>

<!-- Vue 逻辑 -->
<script>
    new Vue({
        el: '#app',
        data() {
            return {
                showDropdown: false, // 控制下拉菜单显示
                isLoggedIn: false,   // 登录状态
                userInfo: {},        // 用户信息
                loading: true,       // 加载状态
                cartItems: [],       // 购物车商品列表
                totalAmount: 0,      // 总金额
                totalItems: 0,       // 商品总数
                cartCount: 0         // 购物车商品数量
            }
        },
        mounted() {
            this.checkLoginStatus();
            this.loadCartData();
        },
        methods: {
            // 检查登录状态
            checkLoginStatus() {
                axios.get('/vegetablemarketexpress/user/checkLoginStatus', {withCredentials: true})
                    .then(response => {
                        if (response.data.code === 200 && response.data.data) {
                            this.isLoggedIn = true;
                            this.userInfo = response.data.data;
                        } else {
                            this.isLoggedIn = false;
                            this.userInfo = {};
                            // 未登录跳转到登录页面
                            window.location.href = 'login.html';
                        }
                    })
                    .catch(error => {
                        console.error('检查登录状态失败:', error);
                        this.isLoggedIn = false;
                        // 出错跳转到登录页面
                        window.location.href = 'login.html';
                    });
            },

            // 加载购物车数据
            loadCartData() {
                this.loading = true;

                // 使用已有的 getCartDetails 接口
                axios.get('/vegetablemarketexpress/cart/getCartDetails', {withCredentials: true})
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            this.cartItems = response.data.data || [];
                            this.calculateTotals();
                        } else {
                            this.cartItems = [];
                            this.calculateTotals();
                        }
                    })
                    .catch(error => {
                        console.error('加载购物车数据失败:', error);
                        this.$message.error('网络错误，加载购物车数据失败');
                        this.cartItems = [];
                        this.calculateTotals();
                    })
                    .finally(() => {
                        this.loading = false;
                    });
            },

            // 计算总金额和总数量
            calculateTotals() {
                this.totalAmount = 0;
                this.totalItems = 0;
                this.cartCount = 0;

                this.cartItems.forEach(item => {
                    const price = parseFloat(item.product.price) || 0;
                    const quantity = parseInt(item.quantity) || 0;
                    this.totalAmount += price * quantity;
                    this.totalItems += quantity;
                    this.cartCount += quantity;
                });
            },

            // 更新商品数量
            updateQuantity(item, change) {
                const newQuantity = parseInt(item.quantity) + change;
                if (newQuantity < 1) return;

                this.updateQuantityAPI(item.cartId, newQuantity);
            },

            // 直接输入数量更新
            updateQuantityInput(item, event) {
                const newQuantity = parseInt(event.target.value);
                if (isNaN(newQuantity) || newQuantity < 1) {
                    event.target.value = item.quantity;
                    return;
                }

                this.updateQuantityAPI(item.cartId, newQuantity);
            },

            // 调用API更新数量（这里需要后端提供更新数量的接口）
            // 调用API更新数量
            updateQuantityAPI(cartId, quantity) {
                // 调用后端更新数量接口
                axios.post('/vegetablemarketexpress/cart/updateQuantity', null, {
                    params: {
                        cartId: cartId,
                        quantity: quantity
                    },
                    withCredentials: true
                })
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            // 更新前端数据
                            this.cartItems.forEach(item => {
                                if (item.cartId === cartId) {
                                    item.quantity = quantity;
                                }
                            });
                            this.calculateTotals();
                            this.$message.success('数量更新成功');
                        } else {
                            this.$message.error('更新失败');
                        }
                    })
                    .catch(error => {
                        console.error('更新数量失败:', error);
                        this.$message.error('网络错误，更新数量失败');
                    });
            },

            // 清空购物车
            clearCart() {
                this.$confirm('确定要清空购物车吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 调用后端接口逐个删除购物车项
                    const deletePromises = this.cartItems.map(item => {
                        return axios.delete('/vegetablemarketexpress/cart/clearCart', {
                            params: { cartId: item.cartId },
                            withCredentials: true
                        });
                    });

                    Promise.all(deletePromises)
                        .then(responses => {
                            // 检查所有删除操作是否成功
                            const allSuccess = responses.every(response =>
                                response.data && response.data.code === 200
                            );

                            if (allSuccess) {
                                this.cartItems = [];
                                this.calculateTotals();
                                this.$message.success('购物车已清空');
                            } else {
                                this.$message.error('部分商品删除失败');
                            }
                        })
                        .catch(error => {
                            console.error('清空购物车失败:', error);
                            this.$message.error('网络错误，清空购物车失败');
                        });
                }).catch(() => {
                    // 取消操作
                });
            },

            // 从购物车移除商品
            removeFromCart(cartId) {
                this.$confirm('确定要从购物车中移除该商品吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 调用后端删除接口
                    axios.delete('/vegetablemarketexpress/cart/removeFromCart', {
                        params: { cartId: cartId },
                        withCredentials: true
                    })
                        .then(response => {
                            if (response.data && response.data.code === 200) {
                                // 从前端列表中移除
                                this.cartItems = this.cartItems.filter(item => item.cartId !== cartId);
                                this.calculateTotals();
                                this.$message.success('商品已移除');
                            } else {
                                this.$message.error('删除失败');
                            }
                        })
                        .catch(error => {
                            console.error('删除商品失败:', error);
                            this.$message.error('网络错误，删除商品失败');
                        });
                }).catch(() => {
                    // 取消操作
                });
            },

            // 清空购物车
            clearCart() {
                this.$confirm('确定要清空购物车吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 这里需要后端提供清空购物车的接口
                    axios.delete('/vegetablemarketexpress/cart/clearCart', {})
                    // 暂时只清空前端数据
                    this.cartItems = [];
                    this.calculateTotals();
                    this.$message.success('购物车已清空');
                }).catch(() => {
                    // 取消操作
                });
            },

            // 处理图片加载错误
            handleImageError(event) {
                event.target.src = '/static/images/no-image.png';
            },
            // 跳转到结算页面
            goToCheckout() {
                if (this.cartItems.length === 0) {
                    this.$message.warning('购物车为空，无法结算');
                    return;
                }
                // 跳转到支付页面
                window.location.href = 'Pay.html';
            },


            // 跳转到个人中心
            goToPersonalCenter() {
                window.location.href = '/vegetablemarketexpress/html/front/personalCenter.html';
            },

            // 跳转到账号管理
            goToAccountManagement() {
                // window.location.href = 'account-management.html';
            },

            // 退出登录
            logout() {
                axios.get('/vegetablemarketexpress/user/logout', { withCredentials: true })
                    .then(response => {
                        if (response.data.code === 200) {
                            this.isLoggedIn = false;
                            this.userInfo = {};
                            this.showDropdown = false;
                            this.$message.success('退出登录成功');
                            window.location.href = 'index.html';
                        } else {
                            this.$message.error('退出登录失败');
                        }
                    })
                    .catch(error => {
                        console.error('退出登录失败:', error);
                        this.$message.error('退出登录失败');
                    });
            },

            goToLogin() {
                window.location.href = 'login.html';
            },

            goToCart() {
                window.location.href = 'cart.html';
            }
        }
    });
</script>
</body>
</html>
